<?php

define('APP_ROOT',  substr(__FILE__, 0, -8));

function D($key) {
  $array  = explode('.',trim($key));
  $count  = count($array);
  $return = $GLOBALS['_D'];
  for($i=0;$i<$count;$i++) {
    $return = $return[$array[$i]];
    if (empty($return)) return $return;
  }
  return $return;
}

function L($key) {
  $array  = explode('.',trim($key));
  $count  = count($array);
  $return = $GLOBALS['_L'];
  for($i=0;$i<$count;$i++) {
    $return = $return[$array[$i]];
    if (empty($return)) return $array[$i];
  }
  return $return;
}

function S($key) {
  $array  = explode('.',trim($key));
  $count  = count($array);
  $return = $GLOBALS['_S'];
  for($i=0;$i<$count;$i++) {
    $return = $return[$array[$i]];
    if (empty($return)) return $return;
  }
  return $return;
}

function C($class, $set='') {
  $class = ucfirst(strtolower($class));
  if(empty($GLOBALS['_C'][$class])) {
    $classFile = APP_ROOT.'includes/class/'.$class.'.php';
    if(file_exists($classFile)) {
      require_once($classFile);
      if($set) {
        $GLOBALS['_C'][$class] = & new $class($set);
      }
      else {
        $GLOBALS['_C'][$class] = & new $class;
      }
    }
    else {
      exit('can\'t load class: '.$class);
    }
  }
  elseif($set) {
    $GLOBALS['_C'][$class] -> setconfig($set);
  }
  return $GLOBALS['_C'][$class];
}

function M($cfile='', $method='') {
  $cfile = preg_replace("/([^A-Za-z0-9_\-])+/",'',strtolower($cfile));
  if($cfile) {
    $file = ROOT_WEB . $cfile .'.php';
  }
  else {
    $file  = APP_ROOT . 'includes/module/index.php';
    $cfile = 'index';
  }
  if(file_exists($file)) {
    require_once($file);
    $class = 'page_' . $cfile;
    $GLOBALS['_M'][$class] = & new $class;
  }
  else {
    exit("error module: $cfile");
  }
  $method = $method ? strtolower($method) : '_default';
  if ($method && method_exists($GLOBALS['_M'][$class],$method)) {
    $GLOBALS['_M'][$class]->$method();
  }
  return $GLOBALS['_M'][$class];
}

function T($file) {
  return C('Template')->getfile($file);
}

function U($str) {
  $e = explode('|',trim($str));
  $arr = array(
    'app'    => $e[0] ? $e[0] : 'index',
    'method' => $e[1] ? $e[1] : '_default',
    'params' =>array()
  );
  $c = count($e);
  for($i=2;$i<$c;$i++) {
    list($k,$v) = explode('=',$e[$i]);
    $k && $arr['params'][$k] = $v;
  }
  return C('Url')->create($arr);
}


function setL($arr,$v='') {
  if($v) {
    $GLOBALS['_L'][$arr] = $v;
  }
  else {
    $arr = (array)$arr;
    foreach($arr as $key=>$val) {
      $GLOBALS['_L'][$key] = $val;
    }
  }
}
function setD($arr,$v='') {
  if($v) {
    $GLOBALS['_D'][$arr] = $v;
  }
  else {
    $arr = (array)$arr;
    foreach($arr as $key=>$val) {
      $GLOBALS['_D'][$key] = $val;
    }
  }
}
function setS($arr,$v='') {
  if($v) {
    $GLOBALS['_S'][$arr] = $v;
  }
  else {
    $arr = (array)$arr;
    foreach($arr as $key=>$val) {
      $GLOBALS['_S'][$key] = $val;
    }
  }
}

?>